package com.gss.plugin.oauth2.handler;

import com.alibaba.fastjson.JSONObject;
import com.gss.entity.R;
import com.gss.entity.enums.ConstantEnum;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author DYang
 * @date 2023/8/20
 * 授权失败403
 */
@Component
public class CustomAuth403Handler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        // 设置响应状态码
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.setHeader("Content-Type","application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();

        R<Object> res = R.error(ConstantEnum.NON_AUTH);
        writer.write(JSONObject.toJSONString(res));
        writer.flush();
        writer.close();

    }
}
